package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;

    @Override
    public PageResult list(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasLength(setmealPageQueryDTO.getName()), "name", setmealPageQueryDTO.getName())
                .eq(setmealPageQueryDTO.getCategoryId() != null, "category_id", setmealPageQueryDTO.getCategoryId())
                .eq(setmealPageQueryDTO.getStatus() != null, "status", setmealPageQueryDTO.getStatus());
        List<Setmeal> setmeals = setmealMapper.selectList(wrapper);
        Page<Setmeal> setmealPage = (Page<Setmeal>) setmeals;
        List<SetmealVO> setmealVOList = setmealPage.stream().map(setmeal -> {
            SetmealVO setmealVO = new SetmealVO();
            BeanUtils.copyProperties(setmeal, setmealVO);
            setmealVO.setCategoryName(categoryMapper.selectById(setmeal.getCategoryId()).getName());
            setmealVO.setSetmealDishes(setmealDishMapper.selectList(new QueryWrapper<SetmealDish>().eq("setmeal_id", setmeal.getId())));
            return setmealVO;
        }).collect(Collectors.toList());
        return new PageResult(setmealPage.getTotal(), setmealVOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.updateById(setmeal);

        Long id = setmeal.getId();
        setmealDishMapper.delete(new QueryWrapper<SetmealDish>().eq("setmeal_id", id));

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (!CollectionUtils.isEmpty(setmealDishes)) {
            setmealDishes.forEach(setmealDish -> {
                setmealDish.setSetmealId(id);
                setmealDishMapper.insert(setmealDish);
            });
        }
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Setmeal setmeal = Setmeal.builder().id(id).status(status).build();
        if (StatusConstant.ENABLE.equals(status)) {
            List<SetmealDish> setmealDishes = setmealDishMapper.selectList(
                    new QueryWrapper<SetmealDish>().eq("setmeal_id", id)
            );
            if (!CollectionUtils.isEmpty(setmealDishes)) {
                setmealDishes.forEach(setmealDish -> {
                    if (StatusConstant.DISABLE.equals(dishMapper.selectById(setmealDish.getDishId()).getStatus())) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }
        setmealMapper.updateById(setmeal);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List<Setmeal> setmeals = setmealMapper.selectByIds(ids);
        if (!CollectionUtils.isEmpty(setmeals)) {
            setmeals.forEach(setmeal -> {
                if (StatusConstant.ENABLE.equals(setmeal.getStatus()))
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            });
            setmealMapper.deleteByIds(ids);
            setmealDishMapper.delete(new QueryWrapper<SetmealDish>().eq("setmeal_id", ids));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmeal.setStatus(StatusConstant.ENABLE);
        setmealMapper.insert(setmeal);
        Long id = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (!CollectionUtils.isEmpty(setmealDishes)) {
            setmealDishes.forEach(setmealDish -> {
                setmealDish.setSetmealId(id);
                setmealDishMapper.insert(setmealDish);
            });
        }
    }

    @Override
    public SetmealVO getById(Long id) {
        Setmeal setmeal = setmealMapper.selectById(id);
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setCategoryName(categoryMapper.selectById(setmeal.getCategoryId()).getName());
        setmealVO.setSetmealDishes(setmealDishMapper.selectList(new QueryWrapper<SetmealDish>().eq("setmeal_id", id)));
        return setmealVO;
    }

    @Override
    public List<Setmeal> listByCategoryId(Long categoryId) {
        return setmealMapper.selectList(new QueryWrapper<Setmeal>()
                .eq("category_id", categoryId)
                .eq("status", StatusConstant.ENABLE)
        );
    }

    @Override
    public List<DishItemVO> listDishItemVO(Long id) {
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(
                new QueryWrapper<SetmealDish>().eq("setmeal_id", id)
        );
        return setmealDishes.stream().map(setmealDish -> {
            Dish dish = dishMapper.selectById(setmealDish.getDishId());
            return DishItemVO.builder()
                    .name(dish.getName())
                    .image(dish.getImage())
                    .copies(setmealDish.getCopies())
                    .description(dish.getDescription())
                    .build();
        }).collect(Collectors.toList());
    }
}
